package com.zyx.wanshu.controller;

import com.zyx.wanshu.entity.Menu;
import com.zyx.wanshu.service.IMenuService;
import com.zyx.wanshu.util.WebUtils;
import com.zyx.wanshu.vo.MenuVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author zyx
 * @since 2022/7/19 00:43
 */
@Controller
@RequestMapping("/wanshu/menu")
@Slf4j
public class MenuController {
    @Autowired
    private IMenuService menuService;

    @Autowired
    private WebUtils webUtils;

    @GetMapping("/list")
    public String list(MenuVO vo, Model model) {
        vo.setPageSize(50);
        MenuVO resVo = menuService.search(vo);
        model.addAttribute("pageUtils", resVo);
        return "sys/menu/menu";
    }

    @GetMapping("/goSaveOrUpdatePage")
    public String goSaveOrUpdatePage(@RequestParam(value = "id", required = false) Integer id,
                                     Model model) {
        if (id != null) {
            // 说明是更新操作
            Menu menu = menuService.getById(id);
            model.addAttribute("menu", menu);
        }
        // 找到所有的一级菜单
        List<Menu> list = menuService.getAll1LevelMenus();
        model.addAttribute("parents", list);
        return "sys/menu/menuUpdate";
    }

    @PostMapping("/saveOrUpdate")
    public String saveOrUpdate(Menu menu) {
        String userName = webUtils.loginUserName();
        if (menu.getId() != null) {
            // 表示更新数据
            menu.setUpdateTime(new Date());
            menu.setUpdateUser(userName);
            menuService.updateById(menu);
        } else {
            // 表示添加数据
            menu.setCreateTime(new Date());
            menu.setCreateUser(userName);
            menuService.save(menu);
        }
        return "redirect:/wanshu/menu/list";
    }

    @GetMapping("/deleteMenu/{id}")
    @ResponseBody
    public String deleteMenu(@PathVariable("id") Integer id) {
        Boolean flag = menuService.deleteMenuById(id);
        log.info("++++++++++++++++++++删除menu成功? {}", flag);
        return flag ? "success" : "error";
    }

}
